import React, { Component } from 'react'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { View, ScrollView, Button, Text } from '@tarojs/components'
import { AtTabBar, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtInput } from 'taro-ui'
import { SpToast, Loading, FilterBar, SpNote, SpNavBar, SpPage, SearchBar } from '@/components'
import S from '@/spx'
import api from '@/api'
import qs from 'qs'
import { withPager, withBackToTop } from '@/hocs'
import { pickBy, getCurrentRoute, isAlipay, isWeb, isAPP, classNames } from '@/utils'
import DistributionGoodsItem from './comps/goods-item'
import { getDtidIdUrl } from '@/utils/helper'
import FilterBlock from './comps/filterblock'

import './goods.scss'

@withPager
@withBackToTop
export default class DistributionGoods extends Component {
  $instance = getCurrentInstance()
  constructor(props) {
    super(props)

    this.state = {
      ...this.state,
      shareInfo: {},
      info: {},
      curFilterIdx: 0,
      filterList: [{ title: '综合' }, { title: '销量' }, { title: '价格', sort: -1 }],
      tabList: [
        {
          title: '推广商品',
          iconType: 'home',
          iconPrefixClass: 'iconfont icon',
          url: '/marketing/pages/distribution/goods',
          urlRedirect: true
        },
        {
          title: '分类',
          iconType: 'category',
          iconPrefixClass: 'iconfont icon',
          url: '/marketing/pages/distribution/good-category',
          urlRedirect: true
        }
      ],
      localCurrent: 0,
      query: {},
      paramsList: [],
      selectParams: [],
      list: [],
      category_list: [],
      goodsIds: [],
      isOpened: false,
      pageSize: 10,
      pageSize1: null,
      keywords: ''
    }
  }

  async componentDidMount() {
    if (!isWeb && !isAPP()) {
      Taro.hideShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
    }
    this.firstStatus = true
    const { status } = this.$instance.router.params
    const { tabList } = this.state
    tabList[1].url += `?status=${status}`
    this.setState(
      {
        query: {
          item_type: 'normal',
          approve_status: 'onsale,only_show',
          is_promoter: true,
          is_shelves: false
        },
        tabList
      },
      () => {
        this.nextPage()
      }
    )
    const query = {
      category_level: 2
    }
    const { list } = await api.distribution.getGoodsCategorylevel(query)
    const nList = pickBy(list, {
      label: 'category_name',
      value: 'category_id'
    })
    this.setState({
      category_list: nList
    })
  }

  async fetch(params) {
    const { userId } = Taro.getStorageSync('userinfo')
    const { page_no: page, page_size: pageSize } = params
    const { selectParams } = this.state
    const query = {
      ...this.state.query,
      page,
      pageSize,
      request_api: 'xcx'
    }

    const { list, total_count: total, item_params_list = [] } = await api.item.distribution_search(query)

    item_params_list.map((item) => {
      if (selectParams.length < 4) {
        selectParams.push({
          attribute_id: item.attribute_id,
          attribute_value_id: 'all'
        })
      }
      item.attribute_values.unshift({
        attribute_value_id: 'all',
        attribute_value_name: '全部',
        isChooseParams: true
      })
    })

    const nList = pickBy(list, {
      img: 'pics[0]',
      item_id: 'item_id',
      goods_id: 'goods_id',
      title: 'item_name',
      desc: 'brief',
      price: ({ price }) => (price / 100).toFixed(2),
      promoter_price: ({ promoter_price }) => (promoter_price / 100).toFixed(2),
      market_price: ({ market_price }) => (market_price / 100).toFixed(2),
      commission_type: 'commission_type',
      promoter_point: 'promoter_point'
    })

    let ids = []
    list.map((item) => {
      ids.push(item.goods_id)
    })

    const param = {
      goods_id: ids,
      user_id: userId
    }

    const { goods_id } = await api.distribution.items(param)

    this.setState({
      list: [...this.state.list, ...nList],
      goodsIds: [...this.state.goodsIds, ...goods_id],
      query
    })

    if (this.firstStatus) {
      this.setState({
        paramsList: item_params_list,
        selectParams
      })
      this.firstStatus = false
    }

    return {
      total
    }
  }

  handleFilterChange = (data) => {
    const { current, sort } = data

    const query = {
      ...this.state.query,
      goodsSort: current === 0 ? null : current === 1 ? 1 : sort > 0 ? 3 : 2
    }

    if (current == this.state.curFilterIdx && current !== 2) {
      return
    }

    if (
      current !== this.state.curFilterIdx ||
      (current === this.state.curFilterIdx && query.goodsSort !== this.state.query.goodsSort)
    ) {
      this.resetPage()
      this.setState({
        list: []
      })
    }

    this.setState(
      {
        curFilterIdx: current,
        query
      },
      () => {
        this.nextPage()
      }
    )
  }

  handleClickParmas = (id, child_id) => {
    const { paramsList, selectParams } = this.state
    paramsList.map((item) => {
      if (item.attribute_id === id) {
        item.attribute_values.map((v_item) => {
          if (v_item.attribute_value_id === child_id) {
            v_item.isChooseParams = true
          } else {
            v_item.isChooseParams = false
          }
        })
      }
    })
    selectParams.map((item) => {
      if (item.attribute_id === id) {
        item.attribute_value_id = child_id
      }
    })
    this.setState({
      paramsList,
      selectParams
    })
  }

  handleClickSearchParams = (type) => {
    if (type === 'reset') {
      const { paramsList, selectParams } = this.state
      this.state.paramsList.map((item) => {
        item.attribute_values.map((v_item) => {
          if (v_item.attribute_value_id === 'all') {
            v_item.isChooseParams = true
          } else {
            v_item.isChooseParams = false
          }
        })
      })
      selectParams.map((item) => {
        item.attribute_value_id = 'all'
      })
      this.setState({
        paramsList,
        selectParams
      })
    }

    this.resetPage()
    this.setState(
      {
        list: []
      },
      () => {
        this.nextPage()
      }
    )
  }

  handleClickItem = async (id) => {
    const { goodsIds, scrollTops } = this.state
    const goodsId = { goods_id: id }
    const idx = goodsIds.findIndex((item) => id == item)
    const isRelease = idx !== -1
    if (!isRelease) {
      const { status } = await api.distribution.release(goodsId)
      if (status) {
        this.setState(
          {
            goodsIds: [...this.state.goodsIds, id],
            scrollTop: scrollTops
          },
          () => {
            S.toast('上架成功')
          }
        )
      }
    } else {
      const { status } = await api.distribution.unreleased(goodsId)
      if (status) {
        goodsIds.splice(idx, 1)
        this.setState(
          {
            goodsIds,
            scrollTop: scrollTops
          },
          () => {
            S.toast('下架成功')
          }
        )
      }
    }
  }

  onShareAppMessage(res) {
    const { userId } = Taro.getStorageSync('userinfo')
    const { info } = res.target.dataset

    // if (isAlipay) {
    //   return new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //       const info = Taro.getStorageSync('shareData')
    //       resolve({
    //         title: info.title,
    //         imageUrl: info.img,
    //         path: getDtidIdUrl(
    //           `/pages/item/espier-detail?id=${info.item_id}&uid=${userId}&shareUserId=${userId}&company_id=${process.env.APP_COMPANY_ID}`,
    //           info.distributor_id
    //         )
    //       })
    //     }, 10)
    //   })
    // }

    const query = {
      id: info.item_id,
      uid: userId,
      shareUserId: userId,
      company_id: process.env.APP_COMPANY_ID
    }
    return {
      title: info.title,
      imageUrl: info.img,
      path: getDtidIdUrl(`/pages/item/espier-detail?${qs.stringify(query)}`, info.distributor_id)
    }
  }

  handleSearchChange = (val) => {
    this.setState({
      query: {
        ...this.state.query,
        keywords: val
      }
    })
  }
  handleOnClear = () => {
    this.setState(
      {
        query: {
          ...this.state.query,
          keywords: ''
        }
      },
      () => {
        this.resetPage()
        this.setState(
          {
            list: [],
            goodsIds: []
          },
          () => {
            this.nextPage()
          }
        )
      }
    )
  }
  handleConfirm = (val = '') => {
    this.setState(
      {
        query: {
          ...this.state.query,
          keywords: val
        }
      },
      () => {
        this.resetPage()
        this.setState(
          {
            list: [],
            goodsIds: []
          },
          () => {
            this.nextPage()
          }
        )
      }
    )
  }
  handleSubmitParams = async (params) => {
    if (!params.hasOwnProperty('category')) {
      params.category = ''
    }
    if (!params.hasOwnProperty('is_shelves')) {
      params.is_shelves = 'false'
    }
    this.setState(
      {
        query: {
          ...this.state.query,
          ...params
        }
      },
      () => {
        this.resetPage()
        this.setState(
          {
            list: [],
            goodsIds: []
          },
          () => {
            this.nextPage()
          }
        )
      }
    )
  }
  handleClick = (current) => {
    const cur = this.state.localCurrent

    if (cur !== current) {
      const curTab = this.state.tabList[current]
      const { url } = curTab

      const fullPath = getCurrentRoute(this.$instance.router).fullPath.split('?')[0]

      if (url && fullPath !== url) {
        Taro.redirectTo({ url })
      }
    }
  }
  shareDataChange = (shareInfo) => {
    this.setState({ shareInfo })
  }
  batchListing = () => {
    this.setState({ isOpened: true })
  }
  pageSizeHandleChange = (e) => {
    this.setState({ pageSize1: e })
  }
  onCancel = () => {
    this.setState({ isOpened: false, pageSize1: '' })
  }
  onConfirm = () => {
    const { pageSize1, query } = this.state
    if (!pageSize1 > 0) return S.toast('请输入正确的数量!')
    api.distribution
      .batchRelgoods({
        pageSize: pageSize1,
        goodsSort: query.goodsSort || null,
        request_api: 'xcx'
      })
      .then((res) => {
        if (res.status) {
          S.toast('批量上架成功')
          this.resetPage()
          this.setState(
            {
              list: [],
              isOpened: false,
              pageSize1: ''
            },
            () => {
              this.nextPage()
            }
          )
        } else {
          this.setState({
            isOpened: false,
            pageSize1: ''
          })
        }
      })
  }
  handleClose = () => {
    this.setState({ isOpened: false })
  }
  render() {
    const { status } = this.$instance.router.params
    const {
      list,
      page,
      goodsIds,
      curFilterIdx,
      filterList,
      query,
      tabList,
      localCurrent,
      isOpened,
      scrollTop,
      pageSize1,
      category_list
    } = this.state
    return (
      <SpPage className='page-distribution-shop-goods'>
        <SpNavBar title='推广商品' leftIconType='chevron-left' fixed='true' />
        <View className='goods-tabs'>
          <SearchBar
            showDailog={false}
            keyword={query ? query.keywords : ''}
            onFocus={() => false}
            onCancel={() => {}}
            onChange={this.handleSearchChange}
            onClear={this.handleOnClear}
            onConfirm={this.handleConfirm.bind(this)}
          />
          {status === 'true' ? (
            <Button className='goods-tabs_but' onClick={this.batchListing}>
              一键上架
            </Button>
          ) : (
            ''
          )}
          {/* <Text
            className={classNames('goods-tabs_shelves')}
            onClick={() => {
              this.setState(
                {
                  query: {
                    ...query,
                    is_shelves: query && !query.is_shelves
                  }
                },
                () => {
                  this.resetPage()
                  this.setState(
                    {
                      list: [],
                      goodsIds: []
                    },
                    () => {
                      this.nextPage()
                    }
                  )
                }
              )
            }}
          >
            {query.is_shelves ? '查看全部' : '查看已上架'}
          </Text> */}
        </View>

        <View className='goods-tabs'>
          <FilterBar
            className='goods-list__tabs'
            custom
            current={curFilterIdx}
            list={filterList}
            onChange={this.handleFilterChange}
          ></FilterBar>
          <FilterBlock
            title='商品筛选'
            category_list={category_list}
            onSubmitParams={this.handleSubmitParams}
          />

          <AtModal isOpened={isOpened} onClose={this.handleClose}>
            <AtModalHeader>一键上架当前列表商品</AtModalHeader>
            <AtModalContent>
              <AtInput
                name='pageSize'
                title='商品数量:'
                type='number'
                value={pageSize1}
                onChange={this.pageSizeHandleChange}
              />
            </AtModalContent>
            <AtModalAction>
              <Button onClick={this.onCancel}>取消</Button>
              <Button style='margin-top:0; color:#21b991;' onClick={this.onConfirm}>
                确定
              </Button>
            </AtModalAction>
          </AtModal>
        </View>

        <ScrollView
          className='goods-list__scroll'
          scrollY
          scrollTop={scrollTop}
          scrollWithAnimation
          onScroll={this.handleScroll}
          onScrollToLower={this.nextPage}
        >
          <View className='goods-list'>
            {list.map((item) => {
              const isRelease = goodsIds.findIndex((n) => item.goods_id == n) !== -1
              return (
                <DistributionGoodsItem
                  key={item.goods_id}
                  info={item}
                  isRelease={isRelease}
                  shareDataChange={this.shareDataChange}
                  status={status}
                  onClick={() => this.handleClickItem(item.goods_id)}
                />
              )
            })}
          </View>
          {page.isLoading ? <Loading>正在加载...</Loading> : null}
          {!page.isLoading && !page.hasNext && !list.length && (
            <SpNote img='trades_empty.png'>暂无数据~</SpNote>
          )}
        </ScrollView>
        <SpToast />
        <AtTabBar fixed tabList={tabList} onClick={this.handleClick} current={localCurrent} />
      </SpPage>
    )
  }
}
